// user.js
import request from "@/utils/request";

// 登录接口 - 处理嵌套响应
export const login = (loginInfo) => {
  return request.post("/app/user/login", loginInfo).then((res) => {
    // 如果后端返回嵌套结构，在这里统一处理
    if (res.data && res.data.data) {
      return {
        ...res,
        data: res.data.data, // 将嵌套的data提升到顶层
      };
    }
    return res;
  });
};

// 其他接口保持不变
export const register = (userInfo) => {
  return request.post("/app/user/register", userInfo);
};

export const createOrder = (orderInfo) => {
  return request.post("/app/orderbase", orderInfo);
};

export const aliPay = (payData) => {
  return request.post("/app/transaction/pay", payData);
};


// export const getOrdersByUserIdAndStatus = (userId, status) => {
//   return request.get(`/app/orderbase/user/${userId}/status/${status}`);
// };

export const getOrdersByUserIdAndAllStatus = (userId) => {
  return request.get(`/app/orderbase/user/${userId}/all-status`);
};
export const getOrderById = (orderId) => {
  return request.get(`/app/orderbase/${orderId}`);
};
export const submitRefund = (orderId, refundAmount) => {
  const formData = new URLSearchParams();
  formData.append("orderId", orderId);
  formData.append("refundAmount", refundAmount);

  return request.post("/app/refund/refund", formData, {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded", // 指定表单格式
    },
  });
};
/**
 * 根据流水ID获取支付流水详情（包含订单信息）
 * @param {Number} flowId 支付流水ID
 * @returns {Promise} 接口返回的Promise对象
 */
export const getPaymentFlowById = (flowId) => {
  return request.get(`/app/transaction/${flowId}`);
};

/**
 * 根据订单ID获取支付流水信息
 * @param {Number} orderId 订单ID
 * @returns {Promise} 接口返回的Promise对象
 */
export const getPaymentFlowByOrderId = (orderId) => {
  return request.get(`/app/transaction/by-order-id/${orderId}`);
};










/**
 * 根据用户ID查询订单列表
 * @param {Number} userId 用户ID
 * @returns {Promise} 接口返回的Promise对象
 */
export const getOrdersByUserId = (userId) => {
  return request.get(`/app/order-detail/user/${userId}`);
};

/**
 * 根据用户ID和订单状态查询订单
 * @param {Number} userId 用户ID
 * @param {Number|null} status 订单状态（可为null，null时查全部）
 * @returns {Promise} 接口返回的Promise对象
 */
export const getOrdersByUserIdAndStatus = (userId, status) => {
  // 拼接路径，状态为null时也会正确传递null作为路径参数
  return request.get(`/app/order-detail/user/${userId}/status/${status}`);
};

/**
 * 根据订单号查询订单详情
 * @param {String} orderNumber 订单号
 * @returns {Promise} 接口返回的Promise对象
 */
export const getOrderByNumber = (orderNumber) => {
  return request.get(`/app/order-detail/number/${orderNumber}`);
};


export default {
 register,
  login,
  createOrder,
  aliPay,
  getOrdersByUserIdAndStatus,  
  getOrderById,
  submitRefund,
  getPaymentFlowById,
  getPaymentFlowByOrderId,
  getOrdersByUserId,           
  getOrderByNumber               
};